//
//  AirViewController.m
//  B
//
//  Created by lanou on 16/5/14.
//  Copyright © 2016年 裴启航. All rights reserved.
//

#import "AirViewController.h"
#define kCity @"http://api.avatardata.cn/Weather/Query?key=b5889e7ef2e44fdd93d9f43eefb1f365&cityname="
#import "SVProgressHUD.h"
@interface AirViewController ()<UIPickerViewDelegate, UIPickerViewDataSource, UIActionSheetDelegate>

{
    NSArray *provinces, *cities, *areas;
}

@property (strong, nonatomic) UIPickerView *ppView;

@property (copy, nonatomic) NSString *country;   // 国家
@property (copy, nonatomic) NSString *state;  // 省
@property (copy, nonatomic) NSString *city;  // 城市
@property (copy, nonatomic) NSString *district; // 区
@property (copy, nonatomic) NSString *street; // 街道
@property (nonatomic) double latitude;
@property (nonatomic) double longitude;

@property (weak, nonatomic) IBOutlet UILabel *city_name; // 城市
@property (weak, nonatomic) IBOutlet UILabel *info; // 天气
@property (weak, nonatomic) IBOutlet UILabel *temperature;  // 温度
@property (weak, nonatomic) IBOutlet UILabel *humidity; // 湿度
@property (weak, nonatomic) IBOutlet UILabel *direct; // 风向
@property (weak, nonatomic) IBOutlet UILabel *date; // 日期
@property (weak, nonatomic) IBOutlet UILabel *moon; // 农历
@property (weak, nonatomic) IBOutlet UILabel *kongtiao;
@property (weak, nonatomic) IBOutlet UILabel *yundong;
@property (weak, nonatomic) IBOutlet UILabel *ziwaixian;
@property (weak, nonatomic) IBOutlet UILabel *ganmao;
@property (weak, nonatomic) IBOutlet UILabel *chuanyi;

@end

@implementation AirViewController
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    //修改导航条标题颜色
    self.navigationItem.title = @"天气情况";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor grayColor],NSForegroundColorAttributeName,nil]];
    if (!_city) {
        [self createPickerView];
    } else {
        [SVProgressHUD showWithStatus:@"加载中..."];
        [self requestData];
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    [SVProgressHUD dismiss];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _city = [[NSUserDefaults standardUserDefaults] objectForKey:@"city"];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"切换城市" style:(UIBarButtonItemStylePlain) target:self action:@selector(changeState)];
}
- (void)requestData {
    [SVProgressHUD showWithStatus:@"加载中..."];
    NSString *city = [_city stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *url = [NSString stringWithFormat:@"%@%@", kCity, city];
    [[AFHTTPSessionManager manager] GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"reason"] isEqualToString:@"Succes"]) {
        [SVProgressHUD dismiss];
        [self.view popMessageWithTitle:@"获取天气成功" postion:(CENTER)];
#pragma mark - 城市天气赋值
            NSDictionary *realtime = responseObject[@"result"][@"realtime"];
            _city_name.text = realtime[@"city_name"];
            _info.text = realtime[@"weather"][@"info"];
            _temperature.text = [NSString stringWithFormat:@"%@°", realtime[@"weather"][@"temperature"]];
            _humidity.text = [NSString stringWithFormat:@"湿度:%@%%", realtime[@"weather"][@"humidity"]];
            _direct.text = [NSString stringWithFormat:@"风向:%@", realtime[@"wind"][@"direct"]];
            _date.text = [NSString stringWithFormat:@"日期:%@", realtime[@"date"]];
            _moon.text = [NSString stringWithFormat:@"农历:%@", realtime[@"moon"]];
            NSDictionary *lifeinfo = responseObject[@"result"][@"life"][@"info"];
            _kongtiao.text = [NSString stringWithFormat:@"空调:%@,%@", lifeinfo[@"kongtiao"][0], lifeinfo[@"kongtiao"][1]];
            _yundong.text = [NSString stringWithFormat:@"运动:%@,%@", lifeinfo[@"yundong"][0], lifeinfo[@"yundong"][1]];
            _ziwaixian.text = [NSString stringWithFormat:@"紫外线:%@,%@", lifeinfo[@"ziwaixian"][0], lifeinfo[@"ziwaixian"][1]];
            _ganmao.text = [NSString stringWithFormat:@"感冒:%@,%@", lifeinfo[@"ganmao"][0], lifeinfo[@"ganmao"][1]];
            _chuanyi.text = [NSString stringWithFormat:@"穿仪:%@,%@", lifeinfo[@"chuanyi"][0], lifeinfo[@"chuanyi"][1]];
        } else {
        [self.view popMessageWithTitle:@"该城市的天气现在还无法获取😭" postion:(CENTER)];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error-%@", error);
    }];
}
- (void)changeState {
    [self createPickerView];
}
- (void)createPickerView
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"\n\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[NSUserDefaults standardUserDefaults] setObject:_city forKey:@"city"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self requestData];
    }]];
    self.ppView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 394, 200)];
    self.ppView.delegate = self;
    self.ppView.dataSource = self;
    [alert.view addSubview:self.ppView];
    
    [self presentViewController:alert animated:YES completion:nil];
    //加载数据
    provinces = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"area.plist" ofType:nil]];
    cities = [[provinces objectAtIndex:0] objectForKey:@"cities"];
    
    self.state = [[provinces objectAtIndex:0] objectForKey:@"state"];
    self.city = [[cities objectAtIndex:0] objectForKey:@"city"];
    
    areas = [[cities objectAtIndex:0] objectForKey:@"areas"];
    if (areas.count > 0) {
        self.district = [areas objectAtIndex:0];
    } else{
        self.district = @"";
    }
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return [provinces count];
            break;
        case 1:
            return [cities count];
            break;
            
        default:
            return [areas count];
            break;
    }
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return [[provinces objectAtIndex:row] objectForKey:@"state"];
            break;
        case 1:
            return [[cities objectAtIndex:row] objectForKey:@"city"];
            break;
        case 2:
            if ([areas count] > 0) {
                return [areas objectAtIndex:row];
                break;
            }
        default:
            return  @"";
            break;
    }
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    switch (component) {
        case 0:
            cities = [[provinces objectAtIndex:row] objectForKey:@"cities"];
            [self.ppView selectRow:0 inComponent:1 animated:YES];
            [self.ppView reloadComponent:1];
            
            areas = [[cities objectAtIndex:0] objectForKey:@"areas"];
            [self.ppView selectRow:0 inComponent:2 animated:YES];
            [self.ppView reloadComponent:2];
            
            self.state = [[provinces objectAtIndex:row] objectForKey:@"state"];
            self.city = [[cities objectAtIndex:0] objectForKey:@"city"];
            if ([areas count] > 0) {
                self.district = [areas objectAtIndex:0];
            } else{
                self.district = @"";
            }
            break;
        case 1:
            areas = [[cities objectAtIndex:row] objectForKey:@"areas"];
            [self.ppView selectRow:0 inComponent:2 animated:YES];
            [self.ppView reloadComponent:2];
            
            self.city = [[cities objectAtIndex:row] objectForKey:@"city"];
            if ([areas count] > 0) {
                self.district = [areas objectAtIndex:0];
            } else{
                self.district = @"";
            }
            break;
        case 2:
            if ([areas count] > 0) {
                self.district = [areas objectAtIndex:row];
            } else{
                self.district = @"";
            }
            break;
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
